﻿// -----------------------------------------------------------------------
//  <copyright file="IdentityService.User.cs" company="OSharp开源团队">
//      Copyright (c) 2014-2015 OSharp. All rights reserved.
//  </copyright>
//  <site>http://www.osharp.org</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2015-12-04 17:14</last-date>
// -----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

using Microsoft.AspNet.Identity;

using OSharp.Core.Identity;
using OSharp.Core.Mapping;
using ZH.JY.Identity.Dtos;
using ZH.JY.Identity.Models;
using OSharp.Utility.Data;
using OSharp.Utility.Extensions;


namespace ZH.JY.Identity
{
    public partial class IdentityService
    {
        /// <summary>
        /// 获取或设置 用户管理器
        /// </summary>
        public UserManager UserManager { get; set; }

        #region Implementation of IIdentityContract

        /// <summary>
        /// 获取 用户信息查询数据集
        /// </summary>
        public IQueryable<User> Users
        {
            get { return UserRepository.Entities; }
        }

        /// <summary>
        /// 检查用户信息信息是否存在
        /// </summary>
        /// <param name="predicate">检查谓语表达式</param>
        /// <param name="id">更新的用户信息编号</param>
        /// <returns>用户信息是否存在</returns>
        public Task<bool> CheckUserExists(Expression<Func<User, bool>> predicate, int id = 0)
        {
            return UserRepository.CheckExistsAsync(predicate, id);
        }

        /// <summary>
        /// 添加用户信息信息
        /// </summary>
        /// <param name="dtos">要添加的用户信息DTO信息</param>
        /// <returns>业务操作结果</returns>
        public async Task<OperationResult>CreateUsers(params UserInputDto[] dtos)
        {
            UserRepository.UnitOfWork.TransactionEnabled = true;
            List<string> names = new List<string>();
            foreach (UserInputDto dto in dtos)
            {
                User user = dto.MapTo<User>();
                IdentityResult result = dto.Password.IsMissing()
                    ? await UserManager.CreateAsync(user)
                    : await UserManager.CreateAsync(user, dto.Password);
                if (!result.Succeeded)
                {
                    return result.ToOperationResult();
                }
                names.Add(user.NickName);
            }
            return await UserRepository.UnitOfWork.SaveChangesAsync() > 0
                ? new OperationResult(OperationResultType.Success, $"用户“{names.ExpandAndToString()}”创建成功")
                : OperationResult.NoChanged;
        }

        /// <summary>
        /// 更新用户信息信息
        /// </summary>
        /// <param name="dtos">包含更新信息的用户信息DTO信息</param>
        /// <returns>业务操作结果</returns>
        public async Task<OperationResult>UpdateUsers(params UserInputDto[] dtos)
        {
            UserRepository.UnitOfWork.TransactionEnabled = true;
            List<string> names = new List<string>();
            foreach (UserInputDto dto in dtos)
            {
                User user = await UserManager.FindByIdAsync(dto.Id);
                if (user == null)
                {
                    return new OperationResult(OperationResultType.QueryNull);
                }
                user = dto.MapTo(user);
                IdentityResult result;
                if (!dto.Password.IsMissing())
                {
                    result = await UserManager.PasswordValidator.ValidateAsync(dto.Password);
                    if (!result.Succeeded)
                    {
                        return result.ToOperationResult();
                    }
                    user.PasswordHash = UserManager.PasswordHasher.HashPassword(dto.Password);
                }
                result = await UserManager.UpdateAsync(user);
                if (!result.Succeeded)
                {
                    return result.ToOperationResult();
                }
                names.Add(dto.NickName);
            }
            return await UserRepository.UnitOfWork.SaveChangesAsync() > 0
                ? new OperationResult(OperationResultType.Success, $"用户“{names.ExpandAndToString()}”更新成功")
                : OperationResult.NoChanged;
        }

        /// <summary>
        /// 删除用户信息信息
        /// </summary>
        /// <param name="ids">要删除的用户信息编号</param>
        /// <returns>业务操作结果</returns>
        public Task<OperationResult> DeleteUsers(params int[] ids)
        {
            return UserRepository.DeleteAsync(ids,
                null,
                async entity =>
                {
                    await UserExtendRepository.DeleteAsync(entity.UserExtend);
                    return entity;
                });
        }

        #endregion
    }
}